#lang racket

(define tolerance 0.00001)

(define (close-enough? v1 v2)
  (< (abs (- v2 v1)) tolerance))

(define (average x y) (/ (+ x y) 2))

(define (i-i good-enough? improvement x)
  (define (iter guess)
    (let ((next (improvement guess)))
      (if (good-enough? guess next)
          next
          (iter next))))
  (iter x))

(define (iterative-improve good-enough? improvement)
  (lambda (x)
    (define (iter guess)
      (let ((next (improvement guess)))
        (if (good-enough? guess next)
            next
            (iter next))))
    (iter x)))

(define (fixed-point transform first-guess)
  ((iterative-improve close-enough? transform) first-guess))

(define (sqrt x)
  (define (root-good-enough? guess v2 x)
    (< (abs (- (* guess guess) x)) tolerance))
  ((iterative-improve (lambda (guess v2) (root-good-enough? guess v2 x)) 
                      (lambda (y) (average y (/ x y))))
   1.0))

(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0)

(sqrt 4)